#! /usr/bin/env sh

getremotefile()
{
	localtmpdir="$(mktemp -d -p $1)"
	localtmpfile="${localtmpdir}/${3}"
	localfile="${1}/${3}"
	backupfile="${localfile}_backup_$(date)"
	megaget --no-progress --path "$localtmpfile" "$2" && echo "Downloaded $2 successfully!"
	mv "$localfile" "$backupfile" && mv "$localtmpfile" "$localfile" && echo "Synced and replaced successfully!"
}

sendremotefile()
{
	megarm "$1"
	megaput --no-progress --path "$1" "$2" && echo "Uploaded $1 successfully!"
}

# CONFIG
SYNCEDDIR=~/docs
SYNCEDFILE=base_ultimate.kdbx
REMOTEFILEPATH=/Root/sync/base_ultimate.kdbx
THRESHOLDINSECONDS=7200 # 2h difference
# CONFIG

test ! -d $SYNCEDDIR && echo "Synced path doesn't exist, quitting..." && exit 1

REMOTEFLINE="$(megals -l --reload | grep "$REMOTEFILEPATH")"
test -z "$REMOTEFLINE" && echo "Failed to get remote file stat, quitting..." && exit 2
REMOTEDATE="$(echo "$REMOTEFLINE" | awk '{ print $5, $6 }')"
LOCALFLINE="$(stat -c %y "${SYNCEDDIR}/${SYNCEDFILE}")"
test -z "$LOCALFLINE" && "Failed to get local file stat, quitting..." && exit 3
LOCALDATE="$(stat -c %y "${SYNCEDDIR}/${SYNCEDFILE}" | sed -e 's/\..*//g')"

echo "Remote: ${REMOTEDATE}"
echo "Local: ${LOCALDATE}"

DIFFSECONDS=$(echo "$(($(date -d "$REMOTEDATE" +%s) - $(date -d "$LOCALDATE" +%s)))")
ABSDIFFSECONDS=$DIFFSECONDS
test $ABSDIFFSECONDS -lt "0" && ABSDIFFSECONDS=$(echo "$ABSDIFFSECONDS * -1" | bc -l)
test $ABSDIFFSECONDS -lt $THRESHOLDINSECONDS && echo "Remote and local are close enough in time (${DIFFSECONDS}s), exitting..." && exit 0

echo "Local and remote are too far apart (${DIFFSECONDS}s), syncing..."
test $DIFFSECONDS -lt "0" && echo "Remote is too old!" && sendremotefile "$REMOTEFILEPATH" "${SYNCEDDIR}/${SYNCEDFILE}"
test $DIFFSECONDS -gt "0" && echo "Local is too old!" && getremotefile "$SYNCEDDIR" "$REMOTEFILEPATH" "$SYNCEDFILE"

exit 0
